package com.service.admin.merchant.controller;

import com.service.admin.framework.log.RequestLog;
import com.service.admin.merchant.controller.rep.CreditLineStatementPageRep;
import com.service.admin.merchant.controller.rep.MemberCreditLineRep;
import com.service.admin.merchant.controller.req.CreditLineUpdateBalanceReq;
import com.service.admin.merchant.service.MerchantCreditLineService;
import com.service.admin.support.MemberMerchantLockUtils;
import com.service.core.rest.BaseController;
import com.service.core.rest.request.PageRequest;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.MultiResponse;
import com.service.core.rest.response.OneResponse;
import com.service.core.rest.response.PageResponse;
import com.service.dao.enums.CoinsEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * 商家信用额度
 *
 * @author xxxx
 * @email xxxx@qq.com
 * @date 2020-04-01 20:13:14
 */
@RestController
@RequestMapping("merchant-credit-line")
public class MerchantCreditLineController extends BaseController {
    @Autowired
    private MerchantCreditLineService merchantCreditLineService;

    @Autowired
    private MemberMerchantLockUtils merchantLockUtils;

    @GetMapping("balance/{merchantId}")
    @RequestLog("授信额度余额")
    public MultiResponse<MemberCreditLineRep> creditLine(@PathVariable("merchantId") Integer merchantId){
        return successQueryMultiResponse(merchantCreditLineService.merchantCreditLine(merchantId));
    }

    @RequestLog("授信额度流水")
    @PostMapping("statement-page/{merchantId}/{coin}")
    public PageResponse<CreditLineStatementPageRep> pageStatement(@PathVariable("merchantId") Integer merchantId, @PathVariable("coin") CoinsEnum coins, PageRequest pageRequest){
        return successQueryPageResponse(merchantCreditLineService.pageStatement(merchantId, coins, pageRequest));
    }

    @RequestLog("修改会员店铺额度")
    @PostMapping("update-balance")
    public BaseResponse updateBalance(@RequestBody @Validated CreditLineUpdateBalanceReq updateBalanceReq) {
        try {
            if (merchantLockUtils.lockCreditLine(updateBalanceReq.getMerchantId(), updateBalanceReq.getCoins().getName())) {
                merchantCreditLineService.updateBalance(updateBalanceReq);
            }
        } finally {
            merchantLockUtils.unlockCreditLine(updateBalanceReq.getMerchantId(), updateBalanceReq.getCoins().getName());
        }
        return successBaseResponse();
    }



}
